package com.gyms.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnBannerClickListener;
import com.classic.okhttp.beans.HVCitiesBean;
import com.classic.okhttp.beans.HVClickInfoBean;
import com.classic.okhttp.beans.HVDiscountProductBean;
import com.classic.okhttp.beans.HVHomePageItemBean;
import com.classic.okhttp.beans.HVProductHomePageBean;
import com.classic.okhttp.beans.HVProductInfoBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IProductService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.gyms.MyApplication;
import com.gyms.R;
import com.gyms.activity.CityActivity;
import com.gyms.activity.MainActivity;
import com.gyms.activity.ProductDetailsActivity;
import com.gyms.activity.SearchActivity;
import com.gyms.activity.SearchResultActivity;
import com.gyms.adapter.AllCourseRecyClerAdapter;
import com.gyms.adapter.LowCourseAdapter;
import com.gyms.adapter.NetworkImageHolderView;
import com.gyms.base.BaseFragment;
import com.gyms.behavior.FabBehavior;
import com.gyms.constant.Constants;
import com.gyms.manager.BannerIntentManger;
import com.gyms.manager.LocationManger;
import com.gyms.manager.StatisticsManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import constant.EventConstant;
import myInterface.OnItemClickLitener;
import refresh.PtrClassicFrameLayout;
import refresh.PtrDefaultHandler;
import refresh.PtrFrameLayout;
import refresh.PtrHandler;
import utils.AnimotionUtils;
import utils.ScreenUtils;
import utils.StringUtils;
import weight.UiEvent;
import weight.head_foot_recyclerView.EndlessRecyclerOnScrollListener;
import weight.head_foot_recyclerView.HeaderAndFooterRecyclerViewAdapter;
import weight.head_foot_recyclerView.LoadingFooter;
import weight.head_foot_recyclerView.RecyclerViewStateUtils;

/**
 * 课程fragment ltx
 */
public class CourseFragment extends BaseFragment implements OnBannerClickListener, OnItemClickLitener {
    @BindView(R.id.search_btn_back)
    TextView mCityTv;//定位城市
    @BindView(R.id.rv_course_home)
    RecyclerView mRvCourseHomeList;
    @BindView(R.id.pf_course_home)
    PtrClassicFrameLayout mPtrHomeCoursse;
    @BindView(R.id.search_framelayout)
    FrameLayout searchFramelayout;
    @BindView(R.id.layout_stick)
    LinearLayout layoutStick;
    @BindView(R.id.ll_all_product)
    LinearLayout mStickProduct;
    @BindView(R.id.fab_back_to_top)
    FloatingActionButton mBackToTop;
    private LowCourseAdapter mLowCourseAdapter;
    private List<HVDiscountProductBean> mDiscountProductBeans = new ArrayList<>();
    private List<HVProductInfoBean> mHomeProductInfoBeans = new ArrayList<>();
//    private AllCourseAdapter allCourseAdapter;
    private AllCourseRecyClerAdapter mAllCourseAdapter;//搜索的产品列表的adapter
    private LinearLayout youhuiLayout;
    //banner
    private List<HVHomePageItemBean> mHVHomePageItemBeans = new ArrayList<>();
    private ConvenientBanner mCbBanner;//banner


    private MainActivity mMainActivity;
    private LocationManger mLocationManger;//定位的manger

    public MyApplication mMyApplication;
    private BannerIntentManger bannerIntentManger;//banner点击管理类
    private RecyclerView mLowCourse;
    private View mHeaderView;

    //刷新
    private boolean isCanLoadMore=true;
    private boolean isRefresh;
    private View mHeaderStick;
    //悬浮相关
    private int mSuspensionHeight;
    private LinearLayoutManager mCourseHomeManager;
    private int mCurrentPosition;
    private int mTempPos=-1;//悬浮的位置

    private OnStickScrollListen mOnStickScrollListen;//悬浮监听

    private LinearLayout mLlAllProduct;

    private FabBehavior mFabBehavior;
    private int mScreenHight=0;//屏幕高度

    private int mScrollHight=0;//向上滚动的高度

    @Override
    protected int getLayoutResId() {
        return R.layout.course_tab;
    }

    @Override
    protected void initView() {
        initData();
        initHead();
        initLowCourseAdapter();
        initCourseHomeAdapter();
        initBanner();
        initBehavior();
    }

    private void initBehavior() {
        mFabBehavior = FabBehavior.from(mBackToTop);
        mScreenHight= ScreenUtils.getScreenHeight(getActivity());
        mFabBehavior.setScreenHight(mScreenHight);
    }

    private void initData() {
        mOnStickScrollListen=new OnStickScrollListen();
        mMainActivity = (MainActivity) getActivity();
        mLocationManger = LocationManger.getInstance(getActivity());
    }

    private void initCourseHomeAdapter() {
        mAllCourseAdapter = new AllCourseRecyClerAdapter(mContext, mHomeProductInfoBeans);
        mCourseHomeManager=new LinearLayoutManager(mContext);
        mCourseHomeManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvCourseHomeList.setLayoutManager(mCourseHomeManager);
        mAllCourseAdapter.setHeadView(mHeaderView);
        mAllCourseAdapter.setHeaderStick(mHeaderStick);
        //上拉加载相关
        HeaderAndFooterRecyclerViewAdapter headerAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mAllCourseAdapter);
        mRvCourseHomeList.setAdapter(headerAndFooterRecyclerViewAdapter);
        mRvCourseHomeList.addOnScrollListener(mOnScrollListener);
    }

    private void initLowCourseAdapter() {
        LinearLayoutManager imgLinearLayoutManager = new LinearLayoutManager(mContext);
        imgLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mLowCourse.setLayoutManager(imgLinearLayoutManager);
        mLowCourseAdapter = new LowCourseAdapter(mContext, mDiscountProductBeans);
        mLowCourse.setAdapter(mLowCourseAdapter);

    }

    private void initHead() {
        mHeaderView = View.inflate(mContext, R.layout.head_course, null);
        mHeaderStick = View.inflate(mContext, R.layout.head_course_stick, null);
        mCbBanner = (ConvenientBanner) mHeaderView.findViewById(R.id.cb_Banner);
        youhuiLayout= (LinearLayout) mHeaderView.findViewById(R.id.youhui_layout);
        mLlAllProduct = (LinearLayout) mHeaderStick.findViewById(R.id.ll_all_product);
        mLowCourse = (RecyclerView) mHeaderView.findViewById(R.id.rl_lowcourse);
      }

    @Override
    protected void initListener() {
        //注册EventBus
        EventBus.getDefault().register(this);
        mPtrHomeCoursse.disableWhenHorizontalMove(true);//解决和ViewPager的冲突
        mPtrHomeCoursse.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                reFlashData(mMyApplication.mHVCitiesBean);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });

        mCityTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, CityActivity.class);
                mContext.startActivity(intent);
                getActivity().overridePendingTransition(R.anim.activity_open, R.anim.activity_stay);
            }
        });
        mLlAllProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //课程首页筛选按钮点击次数
                StatisticsManager.onEvent(mContext, StatisticsManager.Course_All);
                goSearchReSult();

            }
        });
        mLowCourseAdapter.setOnItemClickLitener(new OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                String productId = mDiscountProductBeans.get(position).getProductId();
                // 优惠课程点击量
                HashMap<String, String> map = new HashMap<>();
                map.put("courseid", productId);
                StatisticsManager.onEvent(mContext, StatisticsManager.Course_PreferentialCourse, map);

                Intent intent = new Intent(mContext, ProductDetailsActivity.class);
                intent.putExtra("productId", productId);
                intent.putExtra("Tag", "RecycleView");
                intent.putExtra("mPosition", position);
                startActivity(intent, false);
            }
        });
        mAllCourseAdapter.setOnItemClickLitener(this);
        doStickListen();
    }

    /**
     * 悬浮条
     */

    private void doStickListen() {
        mRvCourseHomeList.addOnScrollListener(mOnStickScrollListen);
    }

    /**
     * 跳转到查找场地
     */

    private void goSearchReSult() {
        Bundle mBundle=new Bundle();
        mBundle.putBoolean(Constants.KEY_IS_GYM_SEARCH,false);
        startActivity(SearchResultActivity.class, mBundle,false);
    }


    @Override
    protected void processLogic() {
        mMyApplication = ((MyApplication) getActivity().getApplication()).getInstance();
        reFlashData(mMyApplication.mHVCitiesBean);
    }

    /**
     * EventBus 接收事件
     *
     * @param uiEvent uiEvent
     */
    @Subscribe
    public void getCity(UiEvent uiEvent) {
        switch (uiEvent.getKey()) {
            case EventConstant.S_CITY: //选择城市
                //刷新课程页面
                mMainActivity.loadingView.show();
                reFlashData(null);
                break;
            case EventConstant.S_MYINFO: //刷新列表
                reFreshCourse();
                break;
            case EventConstant.S_CITY_COURSE:
                reFlashData((HVCitiesBean) uiEvent.getObject());
                break;
        }
    }

    /**
     * 刷新数据
     * @param mHVCitiesBean cityBean
     */
    private void reFlashData(HVCitiesBean mHVCitiesBean) {
        if(StringUtils.isNull(mHVCitiesBean)) {
            mCityTv.setText(mLocationManger.getCurCityName());
        }else {
            mCityTv.setText(mHVCitiesBean.getName());
        }
        getHomepageContent();
        //刷新的时候将pageIndex始终为1
       reFreshCourse();
    }

    @Override
    public void onDestroyView() {
        mRvCourseHomeList.removeOnScrollListener(mOnScrollListener);
        super.onDestroyView();
        EventBus.getDefault().unregister(this);//销毁的时候注销EventBus
    }

    /**
     * 获取bannner和低价课程
     */
    private void getHomepageContent() {
        IProductService.getProductHomePage(getActivity(), mLocationManger.getCityCode(), true, new ObjectCallback<HVProductHomePageBean>() {
            @Override
            public void onSuccess(HVProductHomePageBean response, String message) {
                //加载广告栏
                if (null != response && !StringUtils.isNull(response.getHomePageUrl())) {
                    mHVHomePageItemBeans.clear();
                    mHVHomePageItemBeans.addAll(response.getHomePageUrl());
                    doRefreshBanner(mHVHomePageItemBeans);
                    mCbBanner.setVisibility(View.VISIBLE);
                }else {
                    mCbBanner.setVisibility(View.GONE);
                }
                //加载低价课程
                if (null != response && !StringUtils.isNull(response.getDiscountProduct())&&response.getDiscountProduct().size()>0) {
                    youhuiLayout.setVisibility(View.VISIBLE);
                    mDiscountProductBeans.clear();
                    mDiscountProductBeans.addAll(response.getDiscountProduct());
                    mLowCourseAdapter.notifyDataSetChanged();
                }else {
                    youhuiLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onErrorT(int code, HVProductHomePageBean response, String errorMessage) {

            }

            @Override
            public void onHttpErrorCall(int statusCode) {

            }
        });
    }



    /**
     * 获取课程列表
     */
    private void getCourseList() {
        IProductService.getProductList(getActivity(), mLocationManger.getCityCode(), mLocationManger.longitude, mLocationManger.latitude, "", mPageIndex, PAGESIZE, "","", false, new ObjectCallback<ArrayList<HVProductInfoBean>>() {
            @Override
            public void onSuccess(ArrayList<HVProductInfoBean> response, String message) {
                mMainActivity.dialogDis();
                if (!isRefresh) {
                    RecyclerViewStateUtils.setFooterViewState(mRvCourseHomeList, LoadingFooter.State.Normal);

                } else {
                    mPtrHomeCoursse.refreshComplete();
                    mHomeProductInfoBeans.clear();//刷新清空数据源
                }

                if (null != response && response.size() != 0) {
                    mHomeProductInfoBeans.addAll(response);
                } else {
                    if(!isRefresh){
                        mPageIndex--;
                        RecyclerViewStateUtils.setFooterViewState(mRvCourseHomeList, LoadingFooter.State.TheEnd);
                        isCanLoadMore=false;
                    }
                }
                mAllCourseAdapter.notifyDataSetChanged();
            }

            @Override
            public void onErrorT(int code, ArrayList<HVProductInfoBean> response, String errorMessage) {
                mMainActivity.dialogDis();
                if(isRefresh){
                    if(null!=mPtrHomeCoursse){
                        mPtrHomeCoursse.refreshComplete();
                    }
                }else{
                    mPageIndex--;
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRvCourseHomeList, PAGESIZE, LoadingFooter.State.NetWorkError, mFooterClick);
                }
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                mMainActivity.dialogDis();
                if(isRefresh){
                    mPtrHomeCoursse.refreshComplete();
                }else{
                    mPageIndex--;
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRvCourseHomeList, PAGESIZE, LoadingFooter.State.NetWorkError, mFooterClick);
                }
            }
        });
    }


    @OnClick({R.id.search_framelayout,R.id.ll_all_product,R.id.fab_back_to_top})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_framelayout:
                //课程首页搜索按钮点击
                StatisticsManager.onEvent(mContext, StatisticsManager.Course_Search);
                Bundle mBundle=new Bundle();
                mBundle.putBoolean(Constants.KEY_IS_GYM_SEARCH,false);
                startActivity(SearchActivity.class, mBundle,false);
                break;
            case R.id.ll_all_product:
                //课程首页筛选按钮点击次数
                StatisticsManager.onEvent(mContext, StatisticsManager.Course_All);
                goSearchReSult();
                break;
            case R.id.fab_back_to_top:
                mCourseHomeManager.scrollToPosition(0);
                AnimotionUtils.onHide(mBackToTop);
                mScrollHight=0;
                break;
        }
    }

    /**
     * 初始化Banner
     */
    public void initBanner() {
        bannerIntentManger=new BannerIntentManger(mContext);
        mCbBanner.setCanLoop(true);
        mCbBanner.setPointViewVisible(true);
        mCbBanner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT,0,0, com.bigkoo.convenientbanner.utils.SizeUtils.dp2px(getActivity(),15), com.bigkoo.convenientbanner.utils.SizeUtils.dp2px(getActivity(),15));
        mCbBanner.startTurning(Constants.BANNER_TIME);
        mCbBanner.setOnBannerClickListener(this);
    }

    @Override
    public void onBannerClick(int position) {
        doBannerClick(position);
    }
    /**
     * banner 加载图片处理
     * @param HVHomePageItemBeans banner列表
     */

    private void doRefreshBanner(List<HVHomePageItemBean> HVHomePageItemBeans) {
        List<String> mBannerUrls=new ArrayList<>();//存放场馆Banner的url列表
        for(HVHomePageItemBean mBannerBean : HVHomePageItemBeans){
            mBannerUrls.add(mBannerBean.getPic());
        }
        mCbBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        },mBannerUrls).setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused});
        mCbBanner.setCanLoop(mBannerUrls.size()!=1);//设置是否循环
        mCbBanner.setPointViewVisible(mBannerUrls.size()!=1);//当只有一个的时候隐藏小点
    }
    /**
     * banner的点击事件
     * @param position pos
     */

    private void doBannerClick(int position) {
        //处理图片的点击事件 一般是跳转到广告的详情界面
        HVClickInfoBean clickInfo =mHVHomePageItemBeans.get(position).getClickInfo();
        if(!StringUtils.isNull(clickInfo)) {
            Enum.EnumHomepageAction action = clickInfo.getAction();

            String  key = StatisticsManager.Course_Banner;
            // 统计各项点击次数
            HashMap<String, String> map = new HashMap<>();
            map.put("bannerId", clickInfo.getBannerId() + "");
            StatisticsManager.onEvent(mContext, key, map);

            if(!StringUtils.isNull(clickInfo.getUrl())) {
                String[] gymIds = clickInfo.getUrl().split(";");
                if(gymIds.length > 0) {
                    bannerIntentManger.bannerIntent(clickInfo,action,clickInfo.getTitle(), gymIds);
                }
            }
        }
    }

    /**
     * 刷新课程列表
     */
    public void reFreshCourse(){
        mPageIndex=1;
        isRefresh=true;
        isCanLoadMore=true;
        getCourseList();
        mScrollHight=0;//滚动距离置0
    }

    /**
     * 加载课程列表
     */

    public void doLoadMore(){
        mPageIndex++;
        isRefresh=false;
        getCourseList();
    }

    /**
     * 上拉加载监听
     */

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if(StringUtils.isNull(mRvCourseHomeList)){
                return;
            }
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRvCourseHomeList);
            if(state == LoadingFooter.State.Loading) {
                Log.d("@Cundong", "the state is Loading, just wait..");
                return;
            }

            if (isCanLoadMore) {
                // loading more
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRvCourseHomeList, PAGESIZE, LoadingFooter.State.Loading, null);
                doLoadMore();
            } else {
                //the end
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRvCourseHomeList, PAGESIZE, LoadingFooter.State.TheEnd, null);
            }
        }
    };

    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRvCourseHomeList, PAGESIZE, LoadingFooter.State.Loading, null);
            doLoadMore();
        }
    };

    @Override
    public void onItemClick(View view, int position) {
        Intent intent = new Intent(mContext, ProductDetailsActivity.class);
        intent.putExtra(Constants.FALG_INTENT_PRPDUCT_ID, mHomeProductInfoBeans.get(position).getProductId());
        startActivity(intent, false);
    }

    /**
     * 悬浮监听
     */

    private class OnStickScrollListen extends RecyclerView.OnScrollListener{
            @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                mSuspensionHeight = layoutStick.getHeight();
            }

            @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(StringUtils.isNull(mRvCourseHomeList)){
                    return;
                }
                mScrollHight=mScrollHight+dy;
                mFabBehavior.setScrollHight(mScrollHight);
                if(mScrollHight<mScreenHight){//保证第一页不会出现
                    AnimotionUtils.onHide(mBackToTop);
                }

                if (mAllCourseAdapter.getItemViewType(mCurrentPosition) == AllCourseRecyClerAdapter.S_STICK_HEAD) {//获取当前的类型 是否是空布局
                    View view = mCourseHomeManager.findViewByPosition(mCurrentPosition);//拿到空布局
                    mTempPos=mCurrentPosition + 1;
                    if (view != null) {
                        if (view.getTop() < mSuspensionHeight) {
                            layoutStick.setY(-(mSuspensionHeight - view.getTop()));
                        } else if(view.getTop()==0){
                            layoutStick.setVisibility(View.VISIBLE);
                            layoutStick.setY(0);
                        }else {
                            layoutStick.setY(0);
                        }
                    }
                }

                if (mCurrentPosition != mCourseHomeManager.findFirstVisibleItemPosition()) {
                    mCurrentPosition = mCourseHomeManager.findFirstVisibleItemPosition();
                }
                if(mCurrentPosition>=mTempPos-1&&mTempPos!=-1&&mCourseHomeManager.findFirstCompletelyVisibleItemPosition()!=0){//当前为没有数据的就隐藏
                    mCurrentPosition = mCourseHomeManager.findFirstVisibleItemPosition();
                    layoutStick.setY(0);
                    layoutStick.setVisibility(View.VISIBLE);
                }else{
                    layoutStick.setVisibility(View.GONE);
                }

            }
        }
}

